﻿using EPiMVC.Reflection;
using EPiMVC.Routing;
using EPiServer;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.Globalization;
using EPiServer.Web;

namespace EPiMVC.UrlRewriting
{
    public class MvcUrlRewriteProvider : FriendlyUrlRewriteProvider, IPageResolver
    {
        public PageData GetPageByPath(string path)
        {
            string pathRelative;
            var branch = GetLanguageBranchAndPath(path, out pathRelative);
            if(branch == null)
                branch = LanguageBranch.Load(ContentLanguage.PreferredCulture);
            
            return GetPageFromStartByPath(pathRelative, branch);
        }

        public override bool ConvertToInternal(UrlBuilder url, out object internalObject)
        {
            PageData page = GetPageByPath(url.Path);
            if (page != null && page.TypeHasAttribute<MvcPageAttribute>())
            {
                internalObject = null;
                return false;
            }

            return base.ConvertToInternal(url, out internalObject);
        }

        public virtual string GetFriendlyUrl(PageReference pageLink)
        {
            PageData page = DataFactory.Instance.GetPage(pageLink);
            UrlBuilder url = new UrlBuilder(page.LinkURL);
            ConvertToExternal(url, pageLink, System.Text.Encoding.UTF8);
            return url.ToString();
        }

        public override bool ConvertToExternal(UrlBuilder url, object internalObject, System.Text.Encoding toEncoding)
        {
            bool result = base.ConvertToExternal(url, internalObject, toEncoding);

            if (!result)
                return false;

            string lang = LanguageSelection.GetLanguageFromHost();
            if (url.Path.StartsWith('/' + lang + '/'))
            {
                url.Path = url.Path.Substring(lang.Length + 1);
            }


            return true;
        }
    }
}
